# -*- coding: utf-8 -*-

import pytest

from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService
from appium.options.common.base import AppiumOptions

import time

# 开启服务端
APPIUM_HOST = '127.0.0.1'
APPIUM_PORT = 4723
@pytest.fixture(scope="session")
def start_appium_service():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=60000)
    yield server
    server.stop()

# 创建客户端到服务端的会话 UIA2驱动
def create_appium_session_by_UIA2driver(custom_opts = None):
    options = UiAutomator2Options()
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{APPIUM_HOST}:{APPIUM_PORT}', options=options)

def create_appium_session_by_chromedriver(custom_opts = None):
    options = AppiumOptions()
    options.set_capability("appium:automationName", "Chromium")
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{APPIUM_HOST}:{APPIUM_PORT}', options=options)

# 测试PC上的Chrome
def test_chrome_on_pc(start_appium_service):
    custom_opts = {
        "platformName": "Linux",
        "browserName": "chrome",
    }
    driver = create_appium_session_by_chromedriver(custom_opts)
    
    url = "https://gitee.com/"
    driver.get(url=url)
    assert "Gitee" in driver.title
    driver.quit()

# 测试PC上的Chrome：指定Chrome和ChromeDriver的路径
def test_chrome_on_pc_specify_chrome_and_driver(start_appium_service):
    chromedriver_path = "/home/shengyi/test/chrometest/chromedriver/chromedriver" # 指定ChromeDriver的路径
    chrome_path = "/home/shengyi/test/chrometest/chrome/chrome" # 指定Chrome浏览器的路径
    chromeOptions = {"binary": chrome_path, }
    custom_opts = {
        "platformName": "Linux",
        "browserName": "chrome",
        "appium:executable": chromedriver_path,
        "goog:chromeOptions": chromeOptions
    }
    driver = create_appium_session_by_chromedriver(custom_opts)
    
    url = "https://gitee.com/"
    driver.get(url=url)
    assert "Gitee" in driver.title
    driver.quit()

def test_chrome_on_android(start_appium_service):
    chromedriver_path = "/home/shengyi/test/chromedriver_113/chromedriver" # 指定ChromeDriver的路径
    chromeOptions = {"androidPackage": "com.android.chrome"}
    custom_opts = {
        "platformName": "Linux",
        "browserName": "chrome",
        "appium:executable": chromedriver_path,
        "goog:chromeOptions": chromeOptions
    }
    driver = create_appium_session_by_chromedriver(custom_opts)
    
    url = "https://gitee.com/"
    driver.get(url=url)
    assert "Gitee" in driver.title
    driver.quit()
